import { apiClient } from './apiClient';
import type { 
  ConfigItem, 
  PaginatedResponse,
  CreateConfigRequest,
  UpdateConfigRequest 
} from '@/types';

export interface GetConfigsParams {
  page?: number;
  pageSize?: number;
  search?: string;
  category?: string;
  type?: 'string' | 'number' | 'boolean' | 'json';
  isSecret?: boolean;
}

export interface ConfigBatchOperationParams {
  ids: string[];
  operation: 'delete' | 'enable' | 'disable' | 'backup';
}

class ConfigService {
  private baseUrl = '/api/configs';

  /**
   * 获取配置列表
   */
  async getConfigs(params: GetConfigsParams): Promise<ConfigItem[]> {
    const { data } = await apiClient.get<PaginatedResponse<ConfigItem>>(this.baseUrl, {
      params
    });
    return data.items;
  }

  /**
   * 获取配置详情
   */
  async getConfigById(id: string): Promise<ConfigItem> {
    const { data } = await apiClient.get<ConfigItem>(`${this.baseUrl}/${id}`);
    return data;
  }

  /**
   * 根据键名获取配置
   */
  async getConfigByKey(key: string): Promise<ConfigItem> {
    const { data } = await apiClient.get<ConfigItem>(`${this.baseUrl}/key/${key}`);
    return data;
  }

  /**
   * 创建配置
   */
  async createConfig(config: CreateConfigRequest): Promise<ConfigItem> {
    const { data } = await apiClient.post<ConfigItem>(this.baseUrl, config);
    return data;
  }

  /**
   * 更新配置
   */
  async updateConfig(id: string, config: UpdateConfigRequest): Promise<ConfigItem> {
    const { data } = await apiClient.put<ConfigItem>(`${this.baseUrl}/${id}`, config);
    return data;
  }

  /**
   * 删除配置
   */
  async deleteConfig(id: string): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/${id}`);
  }

  /**
   * 批量删除配置
   */
  async deleteConfigs(ids: string[]): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/batch`, {
      data: { ids }
    });
  }

  /**
   * 批量操作配置
   */
  async batchOperation(params: ConfigBatchOperationParams): Promise<void> {
    await apiClient.post(`${this.baseUrl}/batch-operation`, params);
  }

  /**
   * 获取配置分类列表
   */
  async getConfigCategories(): Promise<string[]> {
    const { data } = await apiClient.get<string[]>(`${this.baseUrl}/categories`);
    return data;
  }

  /**
   * 验证配置键名是否可用
   */
  async validateConfigKey(key: string, excludeId?: string): Promise<boolean> {
    const { data } = await apiClient.get<{ available: boolean }>(`${this.baseUrl}/validate-key`, {
      params: { key, excludeId }
    });
    return data.available;
  }

  /**
   * 获取配置变更历史
   */
  async getConfigHistory(configId: string): Promise<{
    id: string;
    configId: string;
    oldValue: string;
    newValue: string;
    changedBy: string;
    changedAt: string;
    changeReason?: string;
  }[]> {
    const { data } = await apiClient.get<{
      id: string;
      configId: string;
      oldValue: string;
      newValue: string;
      changedBy: string;
      changedAt: string;
      changeReason?: string;
    }[]>(`${this.baseUrl}/${configId}/history`);
    return data;
  }

  /**
   * 刷新配置缓存
   */
  async refreshConfigCache(): Promise<{ success: boolean; message: string }> {
    const { data } = await apiClient.post<{ success: boolean; message: string }>(`${this.baseUrl}/refresh-cache`);
    return data;
  }

  /**
   * 获取配置的运行时值（考虑环境变量覆盖）
   */
  async getConfigRuntimeValue(key: string): Promise<{
    key: string;
    value: string;
    source: 'database' | 'environment' | 'default';
    isOverridden: boolean;
  }> {
    const { data } = await apiClient.get<{
      key: string;
      value: string;
      source: 'database' | 'environment' | 'default';
      isOverridden: boolean;
    }>(`${this.baseUrl}/runtime/${key}`);
    return data;
  }

  /**
   * 导出配置
   */
  async exportConfigs(params?: {
    category?: string;
    includeSecrets?: boolean;
    format?: 'json' | 'yaml' | 'env';
  }): Promise<Blob> {
    const response = await apiClient.get(`${this.baseUrl}/export`, {
      params: {
        format: 'json',
        ...params
      },
      responseType: 'blob'
    });
    return response.data;
  }

  /**
   * 导入配置
   */
  async importConfigs(file: File, options?: {
    overwrite?: boolean;
    validateOnly?: boolean;
  }): Promise<{
    success: number;
    failed: number;
    skipped: number;
    errors: string[];
  }> {
    const formData = new FormData();
    formData.append('file', file);
    if (options?.overwrite) {
      formData.append('overwrite', 'true');
    }
    if (options?.validateOnly) {
      formData.append('validateOnly', 'true');
    }
    
    const { data } = await apiClient.post<{
      success: number;
      failed: number;
      skipped: number;
      errors: string[];
    }>(`${this.baseUrl}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return data;
  }

  /**
   * 备份配置
   */
  async backupConfigs(): Promise<Blob> {
    const response = await apiClient.get(`${this.baseUrl}/backup`, {
      responseType: 'blob'
    });
    return response.data;
  }

  /**
   * 恢复配置
   */
  async restoreConfigs(file: File): Promise<{
    success: boolean;
    message: string;
    restoredCount: number;
  }> {
    const formData = new FormData();
    formData.append('file', file);
    
    const { data } = await apiClient.post<{
      success: boolean;
      message: string;
      restoredCount: number;
    }>(`${this.baseUrl}/restore`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return data;
  }

  /**
   * 搜索配置
   */
  async searchConfigs(query: string, params?: {
    category?: string;
    includeValues?: boolean;
    limit?: number;
  }): Promise<ConfigItem[]> {
    const { data } = await apiClient.get<ConfigItem[]>(`${this.baseUrl}/search`, {
      params: {
        q: query,
        ...params
      }
    });
    return data;
  }

  /**
   * 获取配置统计信息
   */
  async getConfigStats(): Promise<{
    totalConfigs: number;
    configsByCategory: Record<string, number>;
    configsByType: Record<string, number>;
    secretConfigs: number;
    requiredConfigs: number;
  }> {
    const { data } = await apiClient.get<{
      totalConfigs: number;
      configsByCategory: Record<string, number>;
      configsByType: Record<string, number>;
      secretConfigs: number;
      requiredConfigs: number;
    }>(`${this.baseUrl}/stats`);
    return data;
  }

  /**
   * 验证配置值格式
   */
  async validateConfigValue(type: string, value: string): Promise<{
    valid: boolean;
    error?: string;
    suggestion?: string;
  }> {
    const { data } = await apiClient.post<{
      valid: boolean;
      error?: string;
      suggestion?: string;
    }>(`${this.baseUrl}/validate-value`, {
      type,
      value
    });
    return data;
  }
}

export const configService = new ConfigService();